<template>
  <div id="live"
       ref="live">
    <div class="head">
      <div class="word">
        <Dropdown>
          <a href="javascript:void(0)">
            <Icon class="menu"
                  type="md-menu" />
          </a>
          <DropdownMenu slot="list"
                        class="list">
            <DropdownItem>近三分钟高频词汇：</DropdownItem>
            <DropdownItem>
              <span>关键词：声音</span>
              <span>出现次数：15次</span>
            </DropdownItem>
            <DropdownItem>
              <span>关键词：灯光</span>
              <span>出现次数：13次</span>
            </DropdownItem>
            <DropdownItem>
              <span>关键词：灯光</span>
              <span>出现次数：13次</span>
            </DropdownItem>
            <DropdownItem>
              <span>关键词：灯光</span>
              <span>出现次数：13次</span>
            </DropdownItem>
            <DropdownItem>近三分钟高频词汇：</DropdownItem>
            <DropdownItem>
              <span>关键词：声音</span>
              <span>出现次数：15次</span>
            </DropdownItem>
            <DropdownItem>
              <span>关键词：灯光</span>
              <span>出现次数：13次</span>
            </DropdownItem>
            <DropdownItem>
              <span>关键词：灯光</span>
              <span>出现次数：13次</span>
            </DropdownItem>
            <DropdownItem>
              <span>关键词：灯光</span>
              <span>出现次数：13次</span>
            </DropdownItem>
          </DropdownMenu>
        </Dropdown>
        <span class="vocabulary">
          当前高频词汇： 声音 灯光 速度 太快 问题
        </span>
      </div>
      <div class="operate">
        <span @click="showAnswerModal"
              v-if="roleId == 3 ">
          <Icon type="md-paper" /> 课前问卷</span>
        <Icon class="recording-icon" type="md-radio-button-on" v-if="!ifCanRecord"/>
        <span v-if="userId == liveData.id">
          <span @click="startRecord" v-if="ifCanRecord">
            <Icon type="md-videocam" /> 开始录制</span>
          <span @click="endRecord" v-else>
            <img src="">
            <Icon type="md-videocam" /> 结束录制</span>
        </span>
        <span @click="showKeywordModal">
          <Icon type="md-key" /> 关键字搜索</span>
        <span @click="showNotesModal"
              v-if="roleId==3">
          <Icon type="md-create" /> 课堂笔记</span>
        <span @click="showNotesModal"
              v-else-if="roleId==2">
          <Icon type="md-create" /> 教学日志</span>
        <span @click="showEvaluationModal"
              v-if="roleId==3||roleId==4">
          <Icon type="md-star-outline" /> 课程评价</span>
        <img :src="avatorImgPath"
             v-if="avatorImgPath">
      </div>

    </div>
    <div class="item">
      <div class="player"
           :class="{'full-screen':fullScreen}">
        <video ref="videoPlayer"
               id="videoOutput"
               :muted="muted"
               autoplay
               width="100%"
               height="100%"
               poster=""
               @click="playButtonVideo()"
               >
        </video>
        <div class="video-control"
             ref="videoControlBar">
          <div class="left-control control-wrap">
            <div class="control-item"
                 v-show="!playing"
                 id="start"
                 @click="playButton(true)">
              <Icon type="ios-play" style="margin: 0 25px;font-size: 30px; color: #2d8cf0"/>
            </div>
            <!-- <div class="control-item"><Icon type="md-square" /></div> -->
            <div class="control-item"
                 v-show="playing"
                 id="stop"
                 @click="playButton(false)">
              <Icon type="ios-pause" style="margin: 0 25px;font-size: 30px;color: #2d8cf0"/>
            </div>
            <div class="control-item"
                 @click="refresh">
              <Icon type="md-refresh" />
            </div>
          </div>
          <div class="right-control control-wrap" style="padding-right: 30px;">
            <div class="control-item"
                 @click="changeMuted">
              <Icon :type="muted?'md-volume-off':'md-volume-up'" />
            </div>
            <div class="control-item">
              <Slider v-model="volume"
                      style="width:100px;"
                      @on-input="changeVolume">
              </Slider>
            </div>
            <div class="control-item"
                 style="width:85px;">
              <i-switch size="large"
                        v-model="active">
                <span slot="open">弹幕开</span>
                <span slot="close">弹幕关</span>
              </i-switch>
            </div>
            <div class="control-item">
              <Icon v-if="!fullScreen"
                    type="ios-expand"
                    @click="reqFullScreen($refs.live)" />
              <Icon v-else
                    type="ios-browsers-outline"
                    @click="exitFullScreen" />
            </div>
          </div>
        </div>
        <div v-show="false">Set source URL: <input style="width:350px;"
                 ref="address"
                 id="address"
                 type="text"
                 v-model="addressValue"></div>
        <div class="tanmu"
             style="height:calc(150px)"
             ref="barrage_wrap"
             :class="{on:active}"></div>
      </div>
      <div class="chat">
        <Tabs value="name1"
              class="tabs">
          <TabPane label="讨论"
                   name="name1"
                   class="talk">
            <div class="talk-content">
              <scroll :scrollToBottom="true"
                      :data="talkData"
                      ref="scroll">
                <ul class="talk-content-wrap">
                  <li v-for="item in talkData">
                    <div class="name">
                      <Tag v-if="item.role==2" color="primary">老师</Tag>
                      <img :src="imgSrc + item.photo">
                      <span>{{item.name}}</span>
                    </div>
                    <div class="content">{{item.content}}</div>
                  </li>
                </ul>
              </scroll>
            </div>
            <div class="wrap">
            <!--<video :src='"file:///vod/张世杰老师的普通教学课2019-01-28 14:34:52.webm"' id="video" width="400" height="300" autoplay loop="loop"></video>-->
              <Input class="chart-box"
                     @on-enter="sendon"
                     v-model="talkValue"
                     placeholder="请输入内容" />
              <Button type="info"
                      v-on:click="sendon">发送</Button>
            </div>
          </TabPane>
          <TabPane label="成员"
                   name="name2"
                   class="member">
            <ul class="live-members">
              <li class="live-li" v-for="(item,index) in liveMembers">
                <img :src="imgSrc + item.photo">
                <span>{{item.name}}</span>
              </li>
            </ul>
          </TabPane>
        </Tabs>

      </div>
    </div>
    <keywordModal v-if="keywordModalVisible"
                  ref="keywordModal"></keywordModal>
    <evaluationModal v-if="evaluationModalVisible" :userId = "userId"
                     ref="evaluationModal"></evaluationModal>
    <notesModal v-if="notesModalVisible" :userId = "userId"
                ref="notesModal"></notesModal>

    <Modal id="answer-modal" ref="answerModal"
         footer-hide
         v-model="visible"
         @on-cancel="resetAnswerModal"
         width="800px">
    <Form :model="answerList" ref="answerList">
    <div class="wrap">
      <div class="part part1">
        <div class="title">单选题</div>
        <ul class="desc">
          <li v-if="item.exerciseType==0"
              class="item-title"
              v-for="(item,index) in questionnaireInfo"
              :key="index">
            <div>{{index+1}}.{{item.exerciseName}}</div>
            <FormItem class="options">
              <RadioGroup v-model="answerList.answerSingal[index]" @on-change="checkQuestionnairDone()">
                <Radio :label="it.answerOption" v-for="(it,i) in item.exercisesAnswersList" :key="i">
                  <span>{{it.answerOption}}:{{it.answer}}</span>
                </Radio>
              </RadioGroup>
            </FormItem>
          </li>
        </ul>
      </div>
      <div class="part part2" v-if="0">
        <div class="title">多选题</div>
        <ul class="desc">
          <li v-if="item.exerciseType==1"
              class="item-title"
              v-for="(item,index) in questionnaireInfo"
              :key="index">
            <div>{{index+1}}.{{item.exerciseName}}</div>
            <ul class="options">
              <!--<li v-for="it in item.exercisesAnswersList">
                <span>{{it.answerOption}}</span>
                <span>:</span>
                <span>{{it.answer}}</span>
              </li>-->
              <CheckboxGroup v-model="answerList.answerSingal[index]" @on-change="checkChange()">
                  <Checkbox :label="it.answerOption" v-for="(it,i) in item.exercisesAnswersList" :key="i">
                    <span>{{it.answerOption}}</span>
                    <span>:</span>
                    <span>{{it.answer}}</span>
                  </Checkbox>
              </CheckboxGroup>
            </ul>
          </li>
        </ul>
      </div>
      <div class="part part3">
        <div class="title">主观题</div>
        <ul class="desc">
          <li v-if="item.exerciseType==2"
              class="item-title"
              v-for="(item,index) in questionnaireInfo"
              :key="index">
            <div>{{index+1}}.{{item.exerciseName}}</div>
            <FormItem>
              <Input v-model="answerList.answerTextarea[index]"
              type="textarea"
              @on-blur="checkQuestionnairDone()"
              placeholder="在这里输入答案" />
            </FormItem>
          </li>
        </ul>
      </div>
    </div>
    <FormItem>
        <Button type="primary" :disabled="answerCount" @click="handleSubmit('answerList')">提交</Button>
        <Button style="margin-left: 8px" @click="resetAnswerModal">取消</Button>
    </FormItem>
    </Form>
  </Modal>
  </div>
</template>
<script>
import Scroll from '@/components/scroll'
import keywordModal from '../livemodal/keyword-modal'
import evaluationModal from '../livemodal/evaluation-modal'
import notesModal from '../livemodal/notes-modal'
import { getopts, setIceCandidateCallbacks, onError, showSpinner, hideSpinner } from '@/libs/video-control.js'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
import { getUserName } from '@/libs/util'
import { queryQuestionnaireInfo, submitAnswer, queryQuestionnairesId } from '@/api/management.js'
import { getUserInfo } from '@/api/user.js'
import { getLiveList } from '@/api/data.js'

export default {
  components: {
    keywordModal,
    evaluationModal,
    notesModal,
    Scroll
  },
  data () {
    return {
      // 弹幕显示隐藏控制
      active: true,
      talkValue: '',
      height: 0,
      width: 0,
      index: 0,
      danmu: [
        {
          time: 12,
          text: '666',
          color: 'red'
        },
        {
          time: 13,

          text: 'qqqq',
          color: 'green'
        },
        {
          time: 14,

          text: 'wwww',
          color: 'blue'
        },
        {
          time: 16,
          text: '161616',
          color: '#fff'
        },
        {
          time: 18,
          text: '181818',
          color: '#fff'
        }
      ],
      keywordModalVisible: false,
      evaluationModalVisible: false,
      notesModalVisible: false,
      answerModalVisible: false,
      // 音量
      volume: 50,
      // 播放状态
      playing: false,
      // 静音
      muted: false,
      // 是否全屏
      fullScreen: false,
      // 播放视频dom
      videoOutput: '',
      address: "",
      addressValue: "",
      pipeline: "",
      webRtcPeer: "",
      recorder: '', //是否开始录制对象
      args: getopts(location.search, {
        default: {
          // ws_uri: 'ws://192.168.201.178:8888/kurento',
          ws_uri: process.env.KURENTO,
          ice_servers: undefined
        }
      }),
      talkData: [
        // {
        //   role: 1,
        //   name: '张教员',
        //   content: '同学们好'
        // },
      ],
      avatar: '',
      ws: null, //websocket
      groupID: '',
      userName: '',
      playTime: '', //视频开始播放时间
      liveData: {},
      courseId: '',
      courseName: '', // 课程名字
      courseStartTime: '', // 课程开始时间
      questionnairesId: '', // 课前问卷id
      visible: false,
      content: '',
      answerList: {
        answerSingal: [], //单选答案
        // answerMutiply: [], //多选答案
        answerTextarea: [], //主观题答案
      },
      dataForm: {},
      questionnaireName: '',
      questionnaireInfo: [], // 问卷问题列表
      answerDetailBoList: [], // 问卷答案列表
      questionnairParams:{}, // 提交问卷参数
      userId: '',
      photo: '', //头像
      liveMembers: [], // 直播在线成员列表
      imgSrc: process.env.API_ROOT.replace('wisdom-classroom/', '') +'images/photo/', // 直播在线成员列表头像
      ifCanRecord: true, //是否可以录制
      allQuestionFinish: false, // 课前问卷所以问题已答完
      onPlay: true, // 视频是否正在播放
      answerCount: false //是否提交过答卷
    }
  },
  mounted () {
    console.log(this.liveData)
    this.userName = getUserName()
    console.log('用户名：' + this.userName)
    // 播放视频dom初始化
    if (this.args.ice_servers) {
      console.log('Use ICE servers: ' + this.args.ice_servers)
      kurentoUtils.WebRtcPeer.prototype.server.iceServers = JSON.parse(
        this.args.ice_servers
      )
    } else {
      console.log('Use freeice')
    }
    this.videoOutput = this.$refs.videoPlayer
    this.address = this.$refs.address
    // this.addressValue = 'file:///tmp/file.webm'
    // this.addressValue = 'rtsp://192.168.201.187:8554/test'
    this.addressValue = process.env.LIVE
    // 弹幕初始化
    this.send = this.$start(this.$refs.barrage_wrap)
    // 视频初始音量
    this.$refs.videoPlayer.volue = this.volume * 0.01
    // 监听视频播放
    this.$refs.videoPlayer.addEventListener('play', function () {
      this.active = true
      console.log('play')
    })
    // 监听视频暂停
    this.$refs.videoPlayer.addEventListener('pause', function () {
      console.log('pause')
    })
    // 监听视频时间更新
    this.$refs.videoPlayer.addEventListener('timeupdate', function () {
      // console.log('timeupdate')
      // console.log(this.currentTime)
    })
    // 进页面就开始直播
    this.playButton(true)
    getUserInfo(getUserName()).then(res => {
      console.log(res)
      this.userId = res.data.user.id
      this.photo = res.data.user.photo
      console.log(this.userId)
      //连接websocket
      this.initWebsocket();
    })
    // 获取问卷id
    this.getQuestionnareId()
  },
  created () {
    this.liveData = JSON.parse(sessionStorage.getItem("liveData"))
    this.courseId = this.liveData.courseId
    this.courseName = this.liveData.courseName
    this.courseStartTime = this.liveData.courseStartTime
  },
  destroyed () {
    //离开页面时关闭websocket连接
    this.websocketclose();
  },
  computed: {
    ...mapState({
      hasGetInfo: state => state.user.hasGetInfo,
      // userName: state => state.user.userName,
      // userId: state => state.user.userId,
      avatorImgPath: state => state.user.avatorImgPath,
      roleName: state => state.user.roleName,
      roleId: state => state.user.roleId,
      mobile: state => state.user.mobile,
      name: state => state.user.name,
      no: state => state.user.no,
      email: state => state.user.email,
      password: state => state.user.password,
      token: state => state.user.token
    }),
  },
  methods: {
    ...mapActions(['getUserInfo']),
    // 重置问卷弹窗
    resetAnswerModal(){
      console.log('重置问卷弹窗')
      this.visible=false
      this.answerList.answerSingal=[]
      this.answerList.answerTextarea=[]
    },
    //websocket
    //初始化websocket
    initWebsocket () {
      const wsuri = this.$wsLive+'?groupID='+this.courseId + '&userid=' + this.userId + '&token=' + this.token; //ws地址
      console.log(wsuri)
      this.ws = new WebSocket(wsuri);
      this.ws.onopen = this.websocketonopen;
      this.ws.onerror = this.websocketonerror;
      this.ws.onmessage = this.websocketonmessage;
      this.ws.onclose = this.websocketonclose;
    },
    // 建立 web socket 连接成功触发事件
    websocketonopen () {
      if (this.ws.readyState == 0) {
        console.log('websocket连接尚未建立...')
      } else if (this.ws.readyState == 1) {
        console.log('websocket连接已建立!!!')
      }
    },
    // websocket接收服务端数据时触发事件
    websocketonmessage (res) {
      // console.log(res);
      var dataObj = JSON.parse(res.data);
      if (dataObj.command == 11) { //处理返回聊天信息
        var content = dataObj.data.content;//弹幕+聊天内容
        var from = dataObj.data.from;//聊天名字
        //var role = dataObj.data.from;//聊天角色
        var color = dataObj.data.contentAttr.colour;//弹幕颜色
        //var speed = dataObj.data.contentAttr.speed;//弹幕速度
        //01.发送弹幕
        this.send({
          text: content,
          color: color,
          speed: 2
        })
        //02.聊天面板内容更新
        this.talkData.push({
          role: 2,
          name: from,
          photo: this.photo,
          content: content
        })
        //03.聊天面板内容滚动
        this.$nextTick(() => {
          this.$refs.scroll._initScroll()
        })
      } else if (dataObj.command == 12) { //发送成功提醒
        console.log(dataObj.msg)
      } else if(dataObj.command == 9){ // 加入组成功返回
        console.log(dataObj)
        // 获取成员列表请求
        this.websocketsend(JSON.stringify({
          cmd: '17',
          groupid: this.courseId
        }))
      }else if(dataObj.command == 18){ //获取成员列表
        console.log(dataObj)
        let params = {
          "idsList": dataObj.data
        }
        getLiveList(params).then(res => {
          console.log(res)
          this.liveMembers = res.data
        })
      }else if(dataObj.command == 10){ // 有成员退出
        console.log(dataObj)
        this.websocketsend(JSON.stringify({
          cmd: '17',
          groupid: this.courseId
        }))
      }
    },
    // websocket使用 send() 方法发送数据
    websocketsend (agentData) {
      this.ws.send(agentData);
    },
    // websocket使用 close() 方法关闭连接
    websocketclose () {
      this.ws.close();
    },
    websocketonerror (e) {
      console.log("WebSocket连接发生错误");
    },
    // 断开 websocket 连接成功触发事件
    websocketonclose (e) {
      console.log("connection closed (" + e.code + ")");
    },
    playerReadied () {
      console.log('playerReadied')
    },
    // listen event
    onPlayerPlay (player) {
      console.log('player play!', player)
    },
    onPlayerPause (player) {
      // console.log('player pause!', player)
    },
    onPlayerEnded (player) {
      // console.log('player ended!', player)
    },
    onPlayerLoadeddata (player) {
      // console.log('player Loadeddata!', player)
    },
    onPlayerWaiting (player) {
      // console.log('player Waiting!', player)
    },
    onPlayerPlaying (player) {
      // console.log('player Playing!', player)
    },
    onPlayerTimeupdate (player) {
      console.log('player Timeupdate!', player.currentTime())

      // if (this.danmu[this.index]) {
      //   if (
      //     player.currentTime() > this.danmu[this.index].time &&
      //     this.index == this.danmu[this.index].index
      //   ) {
      //     this.send({
      //       text: this.danmu[0].text,
      //       color: this.danmu[0].color,
      //       speed: 3
      //     })
      //     this.index++
      //   }
      // }
      this.danmu.forEach((item, ind) => {
        if (player.currentTime() > item.time && ind == this.index) {
          this.send({
            text: item.text,
            color: item.color,
            speed: 3
          })
          this.index++
        }
      })
    },
    onPlayerCanplay (player) {
      // console.log('player Canplay!', player)
    },
    onPlayerCanplaythrough (player) {
      // console.log('player Canplaythrough!', player)
    },
    // or listen state event
    playerStateChanged (playerCurrentState) {
      // console.log('player current update state', playerCurrentState)
    },
    // player is ready
    playerReadied (player) {
      // seek to 10s
      console.log('example player 1 readied', player)
      player.currentTime(10)
      // console.log('example 01: the player is readied', player)
    },
    change (status) {
      this.$Message.info('开关状态：' + status)
    },
    sendon () {
      //点发送按钮时只发给websocket后台，前端不做操作，等返回时操作一次
      // //01.发送弹幕
      // this.send({
      //   text: this.talkValue,
      //   color: '#fff',
      //   speed: 2
      // })
      // //02.聊天面板内容更新
      // this.talkData.push({
      //   role: 1,
      //   name: '李四',
      //   content: this.talkValue
      // })
      // //03.聊天面板内容滚动
      // this.$nextTick(() => {
      //   this.$refs.scroll._initScroll()
      // })
      //04.发送给websocket后台
      if (this.talkValue && this.talkValue != '') {
        let createTime10 = Math.round(new Date().getTime() / 1000).toString(); //获取当前10位时间戳
        let createTime13 = Math.round(new Date().getTime()).toString(); //获取当前13位时间戳

        //from: "" 消息发送源userId;
        //cmd:11 发送消息命令 11:用户消息;12:系统消息
        //to: "" 课程id
        //chatType: 1 消息类型，暂时用不到
        //msgType: 0 消息内容类型，0是文字
        //content: "" 消息内容
        //ctime: ""  消息创建时间，秒级10位
        //playAt: "1000" 消息在视频总播放时间，毫秒级13位
        //contentAttr: { 消息样式设置
        //  font: "" 消息字体
        //  size: "" 消息字体大小
        //  colour: "" 消息字体颜色
        //}
        this.websocketsend(
          JSON.stringify({
            "from": this.userId,
            "cmd": 11,
            "to": this.courseId,
            "chatType": "1",
            "msgType": "0",
            "content": this.talkValue,
            "ctime": createTime10,
            "playAt": createTime13 - this.playTime,
            "contentAttr": {
              "font": "10",
              "size": "10",
              "colour": "#fff"
            }
          })
        )
      }
      //05.清空输入框内容
      this.talkValue = ''
    },
    danmuSwich () {
      console.log('danmukaiguan')
    },
    // 关键字检索modal
    showKeywordModal () {
      console.log(111)
      this.keywordModalVisible = true
      this.$nextTick(() => {
        this.$refs.keywordModal.init()
      })
    },
    // 课堂笔记modal
    showEvaluationModal () {
      this.evaluationModalVisible = true
      this.$nextTick(() => {
        this.$refs.evaluationModal.init()
      })
    },
    // 课堂评价modal
    showNotesModal () {
      this.notesModalVisible = true
      this.$nextTick(() => {
        this.$refs.notesModal.init()
      })
    },
    // 课前问卷
    showAnswerModal () {
      let questionnairesId = this.questionnairesId
      this.answerModalVisible = true
      this.$nextTick(() => {
        this.initQuestionList(questionnairesId)
      })
    },
    // 获取课前问卷id
    getQuestionnareId(){
      let courseId = this.courseId
      queryQuestionnairesId(courseId).then(res => {
        console.log(res)
        if(res.status == 200){
          this.questionnairesId = res.data
        }
      })
    },
    //开始录制
    startRecord(){
      let _this = this
      
      //播放后才能录制
      if(this.playing == true){
        this.$Message.info('开始录制课程...')
        this.ifCanRecord = false
        if(this.recorder){
          this.recorder.record(function (error) {
            if (error) return onError(error);
            console.log("Recording ...");
            console.log('开始录播了')
          })
        }
      }else{
        this.$Message.error('直播开始后才能录制课程！')
      }
    },
    //结束录制
    endRecord(){
      this.$Message.info('录制课程完成！')
      this.playing = false
      this.ifCanRecord = true
      this.address.disabled = false
        if (this.webRtcPeer) {
          this.webRtcPeer.dispose()
          this.webRtcPeer = null
        }
        if (this.pipeline) {
          console.log('停止录播了')
          this.pipeline.release()
          this.pipeline = null
        }
        hideSpinner(this.videoOutput)
    },
    // 点击视频时暂停和开始
    playButtonVideo(){
      if(this.onPlay==true){
        this.playButton(false)
      }else{
        this.playButton(true)
      }
    },
    // 播放开始、停止
    playButton (flag) {
      let _this = this
      this.playing = flag
      if (flag) {
        // this.$refs.videoControlBar.style.bottom = '-32px';
        // //鼠标移动，视频按钮条出现
        // document.onmousemove=function(event){
        //   this.$refs.videoControlBar.style.bottom = '0'
        // }
        if (!this.addressValue) {
          window.alert('You must set the video source URL first')
          return
        }
        this.address.disabled = true
        showSpinner(this.videoOutput)
        var options = {
          remoteVideo: this.videoOutput
        }
        this.webRtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options, function (
          error
        ) {
          if (error) {
            return console.error(error)
          }
          _this.webRtcPeer.generateOffer(_this.onOffer)
          _this.webRtcPeer.peerConnection.addEventListener(
            'iceconnectionstatechange',
            function (event) {
              if (_this.webRtcPeer && _this.webRtcPeer.peerConnection) {
                console.log(
                  'oniceconnectionstatechange -> ' +
                  _this.webRtcPeer.peerConnection.iceConnectionState
                )
                console.log(
                  'icegatheringstate -> ' +
                  _this.webRtcPeer.peerConnection.iceGatheringState
                )
              }
            }
          )
        })
      } else {
        this.$refs.videoPlayer.pause()
      }
    },
    changeMuted () {
      if (this.muted) {
        this.volume = 50
        this.muted = false
      } else {
        this.volume = 0
        this.muted = true
      }

    },
    // 调节音量
    changeVolume (value) {
      this.$refs.videoPlayer.volume = value * 0.01
    },
    // 切换全屏
    reqFullScreen (el) {
      this.fullScreen = !this.fullScreen
      var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen,
        wscript;

      if (typeof rfs != "undefined" && rfs) {
        rfs.call(el);
        return;
      }

      if (typeof window.ActiveXObject != "undefined") {
        wscript = new ActiveXObject("WScript.Shell");
        if (wscript) {
          wscript.SendKeys("{F11}");
        }
      }
    },
    exitFullScreen (el) {
      this.fullScreen = !this.fullScreen
      var el = document,
        cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen,
        wscript;

      if (typeof cfs != "undefined" && cfs) {
        cfs.call(el);
        return;
      }

      if (typeof window.ActiveXObject != "undefined") {
        wscript = new ActiveXObject("WScript.Shell");
        if (wscript != null) {
          wscript.SendKeys("{F11}");
        }
      }
    },
    //获取问卷问题
    initQuestionList (questionnaireId) {
      this.visible = true
      this.$nextTick(() => {
        queryQuestionnaireInfo(questionnaireId).then(res => {
          this.questionnaireName = res.data.questionnaireName
          this.questionnaireInfo = res.data.questionnaireExercisesList
          console.log(this.questionnaireInfo)
        })
      })
    },
    radioChange(val){
      console.log(val)
    },
    // checkChange(val){
    //   console.log(val)
    // },
    textareaChange(val){
      console.log(val)
    },
    // 检查问卷是否答完
    checkQuestionnairDone(){
      
    },
    //提交课前问卷答案
    handleSubmit (name) {
      let _this = this
      console.log(_this.questionnaireInfo)
      //遍历问题列表
      if(this.questionnaireInfo.length>0){
        for(let i=0;i<_this.questionnaireInfo.length;i++){
          //过滤选项，取跟答案相同的id
          if( _this.questionnaireInfo[i].exercisesAnswersList.length>1){
            var xuanxiangArr = _this.questionnaireInfo[i].exercisesAnswersList.filter(function(opt){
              return (opt.answerOption == _this.answerList.answerSingal[i])
            })
            // console.log(xuanxiangArr)
          }else{
            var xuanxiangObj = _this.questionnaireInfo[i].exercisesAnswersList[0]
            // console.log(xuanxiangObj)
          }
          this.answerDetailBoList.push({
            exerciseId : _this.questionnaireInfo[i].exerciseId,
            answerId: (xuanxiangObj==undefined ? xuanxiangArr[0].answerId : xuanxiangObj.answerId),
            answerContentChoice: _this.answerList.answerSingal[i] || '',
            answerContentSubjective: _this.answerList.answerTextarea[i] || ''
          })
        }
      }
      // 如果答案数组长度大于问题数组长度，截取答案数组后几位
      if(this.answerDetailBoList.length > this.questionnaireInfo.length){
        this.answerDetailBoList.splice(0,this.questionnaireInfo.length)
      }
      this.questionnairParams = {
        questionnaireId : this.questionnairesId,
        answerPerson : this.userId,
        courseId: this.courseId,
        answerDetailBoList : this.answerDetailBoList
      }
      //遍历答案列表，有没答的不可提交（按钮不能点）
      _this.allQuestionFinish = this.answerDetailBoList.every(function(item){
        return (item.answerContentChoice != '' || item.answerContentSubjective != '')
      })
      // alert(_this.allQuestionFinish)
      console.log('--------------答案列表-----------------')
      console.log(this.answerList)
      console.log('--------------组装答案列表-----------------')
      console.log(this.answerDetailBoList)
      if(_this.allQuestionFinish){
         _this.resetAnswerModal() //清空答案
         _this.answerCount = true
        submitAnswer(_this.questionnairParams).then(res => {
          console.log(res)
        }).catch(err => {
          console.log(err)
        })
      }else{
       _this.$Message.error('请检查所有题目是否答完！')
      }
    },
    handleReset (name) {
      this.visible = false
      this.$refs[name].resetFields();
    },
    // 刷新
    refresh () {
      this.$router.go(0)
    },
    onOffer (error, sdpOffer) {
      let _this = this
      if (error) return onError(error)

      kurentoClient(this.args.ws_uri, function (error, kurentoClient) {
        if (error) return onError(error)

        kurentoClient.create('MediaPipeline', function (error, p) {
          if (error) return onError(error)

          _this.pipeline = p

          _this.pipeline.create('PlayerEndpoint', { uri: _this.addressValue }, function (
            error,
            player
          ) {
            if (error) return onError(error)
            // 录播开始加的位置
            if (_this.userId == _this.liveData.id) {
              _this.pipeline.create('RecorderEndpoint', { stopOnEndOfStream: true, uri: "file:///vod/"+_this.courseName +_this.courseNamecourseStartTime+".webm" }, function (error, recorderEndpointA) {
                if (error) return onError(error);
                //保存录播对象
                _this.recorder = recorderEndpointA;
                console.log('保存全局recorder对象')
                console.log(_this.recorder)
                player.connect(recorderEndpointA, function (error) {
                  if (error) return onError(error);
                  // recorderEndpointA.record(function (error) {
                  //   if (error) return onError(error);
                  //   console.log("Recording ...");
                  // });
                });
              });
            }
            // 录播结束的位置
            _this.pipeline.create('WebRtcEndpoint', function (error, webRtcEndpoint) {
              if (error) return onError(error)

              setIceCandidateCallbacks(webRtcEndpoint, _this.webRtcPeer, onError)

              webRtcEndpoint.processOffer(sdpOffer, function (error, sdpAnswer) {
                if (error) return onError(error)

                webRtcEndpoint.gatherCandidates(onError)

                _this.webRtcPeer.processAnswer(sdpAnswer)
              })

              player.connect(
                webRtcEndpoint,
                function (error) {
                  if (error) return onError(error)

                  console.log(
                    'PlayerEndpoint-->WebRtcEndpoint connection established'
                  )

                  player.play(function (error) {
                    if (error) return onError(error)

                    console.log('Player playing ...')
                  })
                }
              )
            })
          })
        })
      })
    },
  }
}
</script>
<style lang="scss">
#live {
  height: 100vh;
  box-sizing: border-box;
  & > .head {
    height: 40px;
    line-height: 40px;
    background: #1d1d1d;
    color: #fff;
    overflow: hidden;
    & > .word {
      float: left;
      font-size: 16px;
      .ivu-dropdown {
        padding: 0 10px;
        .menu {
          font-size: 30px;
        }
        .ivu-select-dropdown {
          background: #1d1d1d;
          width: 300px;
          max-height: 400px;
          overflow: auto;
          .ivu-dropdown-item {
            color: #ccc;
            &:hover {
              background: #1d1d1d;
            }
            & > span:last-of-type {
              float: right;
            }
          }
        }
      }
      & > .vocabulary {
        vertical-align: middle;
        font-size: 14px;
      }
    }
    & > .operate {
      float: right;
      height: 100%;

      & > img {
        width: 30px;
        height: 30px;
        vertical-align: middle;
        margin-right: 10px;
      }
      & > span {
        vertical-align: middle;
        font-size: 14px;
        padding: 0 10px;
        cursor: pointer;
        transition: all .3s;
        &:hover{
          color: #2d8cf0;
        }
      }
    }
  }
  & > .item {
    display: flex;
    height: calc(100% - 40px);
    overflow: hidden;
    & > .player {
      flex: 1;
      height: 100%;
      position: relative;
      &.full-screen {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        z-index: 2;
        background: #000;
      }
      & > .video-control {
        position: absolute;
        display: flex;
        justify-content: space-between;
        border-radius: 4px;
        bottom: 0;
        height: 32px;
        line-height: 32px;
        width: 100%;
        color: #fff;
        background: rgba(0,0,0,.5);
        transition: all 0.8s;
        .control-wrap {
          display: flex;
          .control-item {
            padding: 0 5px;
            font-size: 0;
            cursor: pointer;
            .ivu-icon {
              font-size: 20px;
            }
            .ivu-switch-large {
              width: 66px;
            }
            .ivu-slider {
              margin-top: -2px;
            }
            .ivu-switch-large.ivu-switch-checked:after {
              left: 44px;
            }
          }
        }
      }
      & > .tanmu {
        position: absolute !important;
        left: 0;
        top: 0;
        width: 100%;
        display: none;
        z-index: 1000;
      }
      & > .on {
        display: block;
        font-size: 20px;
      }
    }
    & > .chat {
      position: relative;
      width: 280px;
      flex: 0 0 280px;
      background: #333;
      .tabs {
        height: 100%;
        color: #fff;
        .ivu-tabs-content {
          height: calc(100% - 52px);
        }
        .ivu-tabs-nav {
          width: 100%;
          .ivu-tabs-tab {
            width: calc(50% - 8px);
            text-align: center;
            box-sizing: border-box;
          }
          .ivu-tabs-tab:last-of-type {
            margin: 0;
          }
        }
        .talk {
          height: 100%;
          position: relative;
          padding-bottom: 40px;
          .talk-content {
            position: relative;
            width: 100%;
            height: 100%;
            overflow: hidden;
            .talk-content-wrap {
              padding: 10px;
              & > li {
                & > .name {
                  img{
                    width: 30px;
                    margin-right: 15px;
                    border-radius: 100%;
                    vertical-align: middle;
                  }
                  height: 30px;
                  line-height: 30px;
                  margin-bottom: 5px;
                  color: #2d8cf0;
                }
                & > .content {
                  padding-left: 8px;
                  line-height: 30px;
                }
              }
            }
          }
          .wrap {
            position: absolute;
            bottom: 0;
            display: flex;
            & > .chart-box {
              width: 224px;
            }
          }
        }
      }
    }
  }
}
#answer-modal {
  .wrap {
    .title {
      font-size: 16px;
      font-weight: bold;
      padding: 10px 0;
    }
    .item-title{
      margin-bottom: 15px;
      &>div{
        font-size: 14px;
        font-weight: 500;
      }
    }
    .options{
      display: flex;
      li{
        flex: 1;
      }
    }
  }
}
.live-members{
  padding: 0 20px 30px;
  .live-li{
    margin-bottom: 15px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    color: #2d8cf0;
    img{
      width: 30px;
      margin-right: 15px;
      border-radius: 100%;
      vertical-align: middle;
    }
    span{
      vertical-align: middle;
    }
  }
}
@keyframes recording{
  0%{
    color: #fff;
  }
  100%{
    color: #f00;
  }
}
.recording-icon{
  font-size: 18px;
  color: #f00;
  animation: recording 2s infinite;
  transition: all .3s;
}
</style>
